package cn.imatu.framework.tool.crypto.asymmetric;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.imatu.framework.tool.core.Base64Utils;

import java.security.KeyPair;

/**
 * @author shenguangyang
 */
public class Sm2AsymmetricCrypto extends BaseAsymmetricCrypto {

    public Sm2AsymmetricCrypto() {

    }

    @Override
    public String decrypt(String data, KeyType keyType, String key) {
        SM2 sm2 = SmUtil.sm2(key, null);
        return sm2.decryptStr(data, keyType);
    }

    @Override
    public String encrypt(String data, KeyType keyType, String key) {
        SM2 sm2 = SmUtil.sm2(null, key);
        return sm2.encryptBase64(data, keyType);
    }

    @Override
    public CryptoKeyDto getKey() {
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        String privateKey = Base64Utils.encode(pair.getPrivate().getEncoded());
        String publicKey = Base64Utils.encode(pair.getPublic().getEncoded());

        return CryptoKeyDto.builder()
                .privateKey(privateKey)
                .publicKey(publicKey)
                .build();
    }

    @Override
    public AsymmetricCryptoType type() {
        return AsymmetricCryptoType.SM2;
    }
}
